<?php

class User extends Extension
{
	protected
		$table		= 'members',
		$info		= array(),
		$loggedIn	= false;
	
	public function __construct($host, $user, $pass, $database, $prefix)
	{
		parent::__construct($host, $user, $pass, $database, $prefix);
		
		if (isset($_COOKIE['nova_name'], $_COOKIE['nova_password']))
		{
			if ($this->validate($_COOKIE['nova_name'], $_COOKIE['nova_password']))
			{
				$this->loggedIn = true;
				
				$this->getUserInfo($_COOKIE['nova_name']);
			}
			else
			{
				$this->logout();
			}
		}
	}
	
	public function __get($value)
	{
		return $this->info[$value];
	}
	
	public function getUserInfo($user = null)
	{
		if ($user === null)
		{
			$user = $this->id;
		}
		
		if (is_int($user))
		{
			$type	= 1;
			$user	= (int) $user;
		}
		elseif (is_string($user))
		{
			$type	= 2;
			$user	= $this->makeSafe($user);
		}
		else
		{
			throw new nbwiException();
		}
		
		$where = $type == 1 ? 'id = ' . $user : 'name = "' . $user . '"';
		
		$stmt = $this->where($where)->execute();
		
		if ($user = $_COOKIE['nova_name'])
		{
			$this->info	= $stmt->fetchAssoc();
			
			return true;
		}
		
		return $stmt->fetchAssoc();
	}
	
	public function loggedIn()
	{
		return $this->loggedIn;
	}
	
	public function logout()
	{
		setcookie('nova_name', null, time() - 3600, '/');
		setcookie('nova_password', null, time() - 3600, '/');
		
		unset($_COOKIE['nova_name']);
		unset($_COOKIE['nova_password']);
		
		$this->info		= array();
		$this->loggedIn	= false;
	}
	
	public function validate($username, $password)
	{
		list($username, $password) = $this->makeSafe($username, $password);
		
		$this->fields('COUNT(id) AS valid')->where('name = "' . $username . '"', 'password = "' . $password . '"');
		$stmt = $this->execute();
		
		$row = $stmt->fetchObject();
		
		return $row->valid == 1;
	}
}

?>